<template>
  <div>
    <el-form ref="userForm" :model="formData" :rules="formRules" label-width="220px">
      <!-- 姓名 部门 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="formData.username" size="mini" class="inputW" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 工号 入职时间 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="formData.workNumber" size="mini" class="inputW" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--手机 聘用形式  -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="formData.mobile" size="mini" class="inputW" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门" prop="departmentId">
            <!-- 放置及联部门组件 -->
            <el-cascader
              v-model="departmentVal"
              :props="{label: 'name', value: 'id' , checkStrictly: true}"
              :options="departmentList"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select
              v-model="formData.formOfEmployment"
              size="mini"
              placeholder="请选择"
              class="inputW"
            >
              <el-option label="正式" :value="1" />
              <el-option label="非正式" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="formData.timeOfEntry"
              size="mini"
              type="date"
              value-format="yyyy-MM-dd"
              class="inputW"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="转正时间" prop="correctionTime">
            <el-date-picker
              v-model="formData.correctionTime"
              size="mini"
              type="date"
              class="inputW"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 员工照片 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="员工头像">
            <!-- 放置上传图片 -->
            <upload-img ref="uploadImg" @uploadSuccess="fn" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 保存个人信息 -->
      <el-row type="flex">
        <el-col :span="12" style="margin-left:220px">
          <el-button size="mini" type="primary" @click="submit">保存更新</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { dataToTree2 } from '@/utils/tools'
import UploadImg from '@/components/uploadimg/index.vue'
import { addEmployee, getEmployeeInfo } from '@/api/employee'
export default {
  name: 'Detail',
  components: {
    UploadImg
  },
  props: {},
  data() {
    return {
      departmentList: [],
      departmentVal: [],
      formData: {
        'username': '',
        'mobile': '',
        'formOfEmployment': '',
        'workNumber': '',
        'departmentId': 0,
        'timeOfEntry': '',
        'correctionTime': '',
        'staffPhoto': ''
      },
      formRules: { username: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名为1-4位' }
      ],
      mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
        //   pattern 正则表达式
        pattern: /^1[3-9]\d{9}$/,
        message: '手机号格式不正确',
        trigger: 'blur'
      }],
      formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'blur' }],
      departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
      timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
      correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }, {
        // validator: (rule, value, callback) => {
        // if (this.userInfo.timeOfEntry) {
        //   if (new Date(this.userInfo.timeOfEntry) > new Date(value)) {
        //     callback(new Error('转正时间不能小于入职时间'))
        //     return
        //   }
        // }
        // callback()
        // }
        validator: (rule, value, callback) => {
          // 如果用户没有选择入职日期，则直接返回，不做校验
          if (!this.formData.timeOfEntry) {
            callback()
            return
          }
          // value 是一个字符串，我们通过new Date(value)把字符串转换成了日期对象，然后通过日期对象得到时间戳
          const timeOfEntry = new Date(this.formData.timeOfEntry)
          const correctionTime = new Date(value)
          if (timeOfEntry.getTime() > correctionTime.getTime()) {
            callback(new Error('入职日期不能大于转正日期'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }]

      }

    }
  },
  computed: {},
  watch: {},
  created() {
    const p1 = this.getDepartmentList()
    console.log(this)
    this.getDepartmentList()
    // 根据url上有没有id来判断是新增还是编辑
    if (this.$route.params.id) {
      const p2 = this.getEmployeeInfo()
      Promise.all([p1, p2]).then(res => {
        // 通过Promise.all实现当员工的详情数据和部门列表数据都获取到后再执行：this.getAllDepartmentIds()
        this.getAllDepartmentIds(this.formData.departmentId)
      })
    }
  },
  mounted() {},
  methods: {
    fn(val) {
      this.formData.staffPhoto = val
    },
    async getEmployeeInfo() {
      const { data } = await getEmployeeInfo(this.$route.params.id)
      this.formData = data
      this.$refs.uploadImg.initImgUrl(data.staffPhoto)
      setTimeout(() => {
        this.getAllDepartmentIds(data.departmentId)
      }, 2000)
    },
    // 给一个id，找出它的父节点的id，以及父节点的父节点id....
    getAllDepartmentIds(id) {
      const o = this.oData.find(item => item.id === id)
      this.departmentVal.unshift(o.id)
      // 由于任何的引用数据类型，只有没有深拷贝过，那么它在内存中永远只有一份。所以通过this.oData找到的o对象就是this.departmentList中的对象
      if (o.pid) {
        this.getAllDepartmentIds(o.pid)
      }
    },
    async getDepartmentList() {
      const { data } = await getDepartmentList()
      // console.log(data)
      // this.data = dataToTree(data)
      // 保存原始数据
      this.oData = data
      // 保存处理后的数据
      this.departmentList = dataToTree2(data)
      console.log(this.departmentList)
      this.deleteEmptyChildren(this.departmentList[0])
    },
    deleteEmptyChildren(o) {
      if (o.children.length > 0) {
        o.children.forEach(obj => {
          this.deleteEmptyChildren(obj)
        })
      } else {
        // 删除这孩子
        delete o.children
      }
    },
    handleChange(val) {
      this.formData.departmentId = val[val.length - 1]
    },
    submit() {
      console.log(1111)
      this.$refs.userForm.validate(async flag => {
        if (!flag) return
        // 发送请求
        await addEmployee(this.formData)
        this.$message.success('添加成功')
      })
    } }
}
</script>

<style scoped lang="scss">
.edit-form {
  background: #fff;
  padding: 20px;
  .inputW {
    width: 380px;
  }
}
</style>
